// index.js  
const util = require('../../utils/utils.js') ;
const mock = require('../../utils/mockData.js') ;
Page({
  data: { 
    currentDate: '',
    
    currentTab: 'rise', // 当前选中榜单 
    riseList: [],      // 涨幅榜数据 
    fallList: [],       // 跌幅榜数据 
    volumeList: [],   // 成交榜数据 
    speedList: [],

       // ✅ 新增：指数数据和涨跌家数
    indexData: [], // 上证、深证、创业板
    riseCount: 0,
    fallCount: 0,
    flatCount: 0,

    // ✅ 新增：头条新闻数据
    // ✅ 新增字段：同花顺头条
headlines: [],

     isLogin: false,
     avatarUrl: '/images/default-avatar.png',
     userId: '', 
     showPopup: false
   },
  
   onShow() {
    this.setData({
      currentDate: util.formatDate(new Date())
    });
  
    this.checkLoginStatus();
  
    this.waitForStockData().then(() => {
      this.loadStockLists();
      this.fetchHeadlines(); // ✅ 调用抓取方法
      // this.updateTimer = setInterval(() => {
      //   this.loadStockLists();
      // }, 5000);
    });

    // ✅ 新增：加载指数行情
    this.loadIndexData();
  },
  goRecommend() {
    wx.navigateTo({
      url: '/pages/recommend/recommend'
    });
  },
// ✅ 新增方法：加载同花顺头条数据
fetchHeadlines() {
  wx.request({
    url: 'https://news.10jqka.com.cn/hotnews_list/',
    method: 'GET',
    header: {
      'Content-Type': 'text/html'
    },
    success: res => {
      const html = res.data;

      // 正则提取链接和标题（提取 a 标签中包含 "title" 的内容）
      const regex = /<a[^>]*href="([^"]+)"[^>]*title="([^"]+)"[^>]*>/g;
      const matches = [...html.matchAll(regex)];

      const headlines = matches.slice(0, 5).map(match => ({
        url: match[1],
        title: match[2]
      }));

      this.setData({ headlines });
    },
    fail: err => {
      console.error('❌ 获取头条失败', err);
      wx.showToast({ title: '头条获取失败', icon: 'none' });
    }
  });
},

// ✅ 新增：跳转到新闻详情页（改为 newsDetail2）
 // 点击跳转到新闻详情页
 goToNewsDetail(e) {
  const url = encodeURIComponent(e.currentTarget.dataset.url);
  const title = encodeURIComponent(e.currentTarget.dataset.title);
  wx.navigateTo({
    url: `/pages/newsDetail2/newsDetail2?url=${url}&title=${title}`
  });
},



// ✅ 修复版：加载上证/深证/创业板指数，避免 NaN
loadIndexData() {
  wx.request({
    url: 'https://hq.sinajs.cn/list=sh000001,sz399001,sz399006',
    success: res => {
      // ✅ 修改①：过滤掉空行，避免 NaN
      const lines = res.data.split('\n').filter(line => line.includes('var hq_str'));
      const indexData = lines.map(line => {
        const parts = line.split(',');
        const codeName = line.split('=')[0].split('_')[2]; // 取指数代码，如 sh000001

        // ✅ 修改②：为不同指数代码赋中文名
        let name = '';
        if (codeName === 'sh000001') name = '上证指数';
        else if (codeName === 'sz399001') name = '深证成指';
        else if (codeName === 'sz399006') name = '创业板指';
        else name = codeName;

        return {
          name,
          price: parseFloat(parts[3]).toFixed(2),
          change: (parts[3] - parts[2]).toFixed(2),
          percent: (((parts[3] - parts[2]) / parts[2]) * 100).toFixed(2)
        };
      });

      this.setData({ indexData }); // ✅ 修改③：安全设置指数数据
    },
    fail: err => console.error('指数获取失败:', err)
  });
},


  waitForStockData() {
    return new Promise((resolve) => {
      const check = () => {
        if (getApp().globalData.allStocks && getApp().globalData.allStocks.length > 0) {
          console.log('✅ 成功读取到 globalData.allStocks');
          resolve();
        } else {
          console.log('⌛ 等待全局股票数据...');
          setTimeout(check, 300); // 每300ms检查一次
        }
      };
      check();
    });
  },    
  onUnload() {
    clearInterval(this.updateTimer);
  },
  loadStockLists() {
    const stocks = getApp().globalData.allStocks || [];
  
    console.log('🏷️ index接收到的 allStocks：', stocks);
    if (stocks.length === 0) {
      console.warn('📭 无股票数据');
      return;
    }
  
    const mappedStocks = stocks
    .filter(item => item && item.code && item.name)

      .map(item => {
        const current = parseFloat(item.currentPrice);
        const prevClose = parseFloat(item.yesterdayClose);
        const open = parseFloat(item.todayOpen);
        const tradedAmount = (parseFloat(item.tradedAmount) || 0) / 10000; // 单位换成 亿

  
        const changeRate = ((current - prevClose) / prevClose) * 100;
        const speedRate = ((current - open) / open) * 100;
  
        return {
          code: item.code,
          name: item.name,
          price: current.toFixed(2),
          changeRate: changeRate.toFixed(2),
          tradedAmount: tradedAmount.toFixed(2), // 保留两位小数

          speedRate: speedRate.toFixed(2), // ✅ 新增涨速字段
          sortChange: changeRate,
          sortSpeed: speedRate
        };
      });
  
      const riseList = mappedStocks
      .filter(stock => stock.sortChange >= 0)
      .sort((a, b) => b.sortChange - a.sortChange);
    
    const fallList = mappedStocks
      .filter(stock => stock.sortChange <= 0)
      .sort((a, b) => a.sortChange - b.sortChange);
    
    const volumeList = [...mappedStocks].sort((a, b) => b.tradedAmount - a.tradedAmount);
    const speedList = [...mappedStocks].sort((a, b) => b.sortSpeed - a.sortSpeed); // ✅ 新增涨速榜排序
  // ✅ 修复④：确保统计涨跌平家数
const riseCount = mappedStocks.filter(s => s.sortChange > 0).length;
const fallCount = mappedStocks.filter(s => s.sortChange < 0).length;
const flatCount = mappedStocks.length - riseCount - fallCount;

    
    const sectors = mappedStocks.map(stock => ({
      name: stock.name,
      code: stock.code, // ✅ 加上 code
      change: (stock.sortChange >= 0 ? '+' : '') + stock.sortChange.toFixed(2) + '%',
      isRise: stock.sortChange >= 0
    }));
    
    
    this.setData({
      riseList,
      fallList,
      volumeList,
      speedList,
      riseCount,      // ✅ 修改⑤：设置涨家数
      fallCount,      // ✅ 修改⑥：设置跌家数
      flatCount       // ✅ 修改⑦：设置平盘数
    });
    
  },
  
  
  

  // 👇 新增：检查登录状态
  async checkLoginStatus() {
    try {
      const res = await wx.cloud.callFunction({ name: 'getOpenId' });
      const openid = res.result.openid;
      const db = wx.cloud.database();
      const userRes = await db.collection('user').where({ openid }).get();

      if (userRes.data.length > 0 && userRes.data[0].isLogin) {
        this.setData({
          isLogin: true,
          avatarUrl: userRes.data[0].avatarUrl || '/images/default-avatar.png',
          userId: 'mx_' + (userRes.data[0].phone || '未知用户') 
        });
      } else {
        this.setData({ isLogin: false });
      }
    } catch (e) {
      console.error('检查登录状态失败', e);
    }
  },



  onLoad() {
    this.setData({ 
      riseList: mock.generateStockData('rise'), 
      fallList: mock.generateStockData('fall'), 
      volumeList: mock.generateStockData('volume') 
    })
    // 加载页面数据
    console.log('Index page loaded');

    // 在页面加载时调用 wx.login 获取 openid
    wx.login({
      success: res => {
        if (res.code) {
          wx.cloud.callFunction({
            name: 'getOpenId', // 确保你在云函数部署时使用的是这个函数名
            data: {
              code: res.code
            },
            success: res => {
              console.log('获取 openid 成功:', res.result.openid);
              console.log('session_key:', res.result.session_key); // ✅ 新增这一行
              
              wx.showToast({
                title: '获取openid成功',
                icon: 'success'
              });
            },
            fail: err => {
              console.error('调用云函数失败:', err);
              wx.showToast({
                title: '获取失败',
                icon: 'error'
              });
            }
          })
        } else {
          console.error('wx.login 失败:', res.errMsg)
        }
      }
    })
  },

// ✅ 新增：点击登录按钮或“切换手机号”
  goToLogin() {
    this.setData({ showPopup: false });
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  // ✅ 新增：点击头像显示弹出框
  showPopup() {
    this.setData({ showPopup: true });
  },

  // ✅ 新增：关闭弹出框
  hidePopup() {
    this.setData({ showPopup: false });
  },

  // ✅ 新增：退出登录逻辑
  async logout() {
    try {
      const res = await wx.cloud.callFunction({ name: 'getOpenId' });
      const openid = res.result.openid;
      const db = wx.cloud.database();
      const userRes = await db.collection('user').where({ openid }).get();

      if (userRes.data.length > 0) {
        await db.collection('user').doc(userRes.data[0]._id).update({
          data: { isLogin: false }
        });

        wx.showToast({
          title: '退出登录成功',
          icon: 'success'
        });

        this.setData({
          isLogin: false,
          showPopup: false
        });
      }
    } catch (err) {
      console.error('退出登录失败:', err);
    }
  },


  

  // 切换榜单标签 
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab  
    this.setData({  currentTab: tab })
  },

  goToStockDetail(e) {
    const code = e.currentTarget.dataset.code;
    const name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: `/pages/stock/stock?name=${encodeURIComponent(name)}&code=${code}`
    });
  }
  
  
});


// login.js 中登录成功后示例代码
async function onLoginSuccess(phone, openid, session_key) {
  const db = wx.cloud.database();
  const userRes = await db.collection('user').where({ openid }).get();

  if (userRes.data.length === 0) {
    // 新用户，添加并设置登录状态为 true
    await db.collection('user').add({
      data: {
        phone,
        openid,
        session_key,
        isLogin: true // 👈 新增：登录状态设置为true
      }
    });
  } else {
    // 老用户，更新登录状态为 true
    await db.collection('user').doc(userRes.data[0]._id).update({
      data: {
        phone,
        session_key,
        isLogin: true // 👈 新增：登录状态设置为true
      }
    });
  }
  

}
